﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FYP14
{
    public partial class AddVisit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetAllAppointments();
                if (Request.QueryString["ID"] != null)
                {
                    SetValues(Convert.ToInt32(Request.QueryString["ID"]));
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Visit oVisit = new Visit();
            oVisit.Appointment_ID = Convert.ToInt32(ddlAppointment.SelectedValue);
            oVisit.Visit_Date = Convert.ToDateTime(((TextBox)(dtcdate.FindControl("TextBox1"))).Text);

            if (Request.QueryString["ID"] != null)
            {
                oVisit.Visit_ID = Convert.ToInt32(Request.QueryString["ID"]);
                BAL.UpdateVisit(oVisit);
            }
            else
            {
                BAL.SaveVisit(oVisit);
            }

            Response.Redirect("ViewVisits.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewVisits.aspx");
        }

        private void SetValues(Int32 ID)
        {
            DataTable dt = BAL.GetVisit(ID);
            if (dt.Rows.Count > 0)
            {
                ddlAppointment.Items[ddlAppointment.Items.IndexOf(ddlAppointment.Items.FindByValue(dt.Rows[0]["appointment_id"].ToString()))].Selected = true;
                ((TextBox)(dtcdate.FindControl("TextBox1"))).Text = dt.Rows[0]["visit_Date"].ToString();
            }
        }

        private void GetAllAppointments()
        {
            DataTable dt = BAL.GetAllAppointments();
            ddlAppointment.DataTextField = "appointment_type";
            ddlAppointment.DataValueField = "appointment_id";
            ddlAppointment.DataSource = dt;
            ddlAppointment.DataBind();
        }
    }
}